package com.yicong.ants.scenic

import android.app.AlertDialog
import android.os.Bundle
import android.text.Html
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.toolbox.util.banner.IBannerItem
import com.yicong.ants.R
import com.yicong.ants.databinding.LayoutBuyTicketDesDialogBinding
import com.yicong.ants.databinding.LayoutPriceCalenderBinding
import com.yicong.ants.databinding.PayOrderDialogBinding
import com.yicong.ants.databinding.ScenicDetailFragmentBinding
import com.yicong.ants.databinding.ScenicDetailTicketListItemBinding
import com.yicong.ants.databinding.ScenicTicketLayoutItemBinding
import com.yicong.ants.databinding.TicketDialogBinding
import com.yicong.ants.manager.UserManager
import com.yicong.ants.scenic.adapter.CalendarAdapter
import com.yicong.ants.scenic.adapter.WeatherInfoAdapter
import com.yicong.ants.scenic.banner.BannerAdapter
import com.yicong.ants.scenic.data.PriceDay
import com.yicong.ants.scenic.data.Ticket
import com.yicong.ants.scenic.data.WeatherInfoItem
import com.yicong.ants.scenic.dialog.SelectItemDialog
import com.yicong.ants.scenic.viewModel.ScenicViewModel
import com.yicong.ants.utils.GlideImageGetter
import com.youth.banner.indicator.BaseIndicator
import com.zx.sdk.util.ConfigHelper
import java.util.Calendar
import java.util.Date
import java.util.Locale

class ScenicDetailFragment : Fragment() {
    private lateinit var binding: ScenicDetailFragmentBinding
    private val scenicViewModel: ScenicViewModel by activityViewModels()
    private val args: ScenicDetailFragmentArgs by navArgs()
    private var mode = 0;
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        BarUtils.setStatusBarLightMode(requireActivity(), true);
        binding = ScenicDetailFragmentBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.backBtn.setOnClickListener { findNavController().navigateUp() }
        binding.backBtn2.setOnClickListener { findNavController().navigateUp() }
        scenicViewModel.scenicDetail.observe(viewLifecycleOwner) {
            it?.bindProgressBar(binding.progressBar)
                ?.onComplete {
                    binding.data = it.data
                    it.data?.images?.let { images ->
                        binding.banner.setIndicator(
                            object : BaseIndicator(requireContext()) {
                                private var indicator: View? = null
                                override fun getIndicatorView(): View {
                                    if (indicator == null) {
                                        indicator = LayoutInflater.from(context)
                                            .inflate(R.layout.scenic_indicator, null, false)
                                    }
                                    return indicator!!
                                }

                                override fun onPageSelected(position: Int) {
                                    super.onPageSelected(position)
                                    indicator?.findViewById<TextView>(R.id.titleTv)?.text =
                                        "${config.currentPosition + 1}/${config.indicatorSize}"
                                }

                                override fun onPageChanged(count: Int, currentPosition: Int) {
                                    super.onPageChanged(count, currentPosition)
                                    indicator?.findViewById<TextView>(R.id.titleTv)?.text =
                                        "${currentPosition + 1}/$count"
                                }
                            }
                        ).setAdapter(BannerAdapter(images.map { image ->
                            object : IBannerItem {
                                override fun getImgUrl() = image

                                override fun getUrl() = ""
                            }
                        }, R.layout.scenic_banner_item))
                    }
                    binding.openTimeBtn.setOnClickListener {
                        val dialogBinding = TicketDialogBinding.inflate(layoutInflater)
                        AlertDialog.Builder(requireActivity()).setCancelable(false)
                            .setView(dialogBinding.root)
                            .show().apply {
                                window?.setBackgroundDrawable(null)
                                dialogBinding.okBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.closeBtn.setOnClickListener {
                                    dismiss()
                                }
                                dialogBinding.titleTv.text = "购票说明"
                                dialogBinding.messageTv.text = binding.data?.openTime
                            }
                    }
                    scenicViewModel.getWeather(
                        requireActivity() as BaseTitleBarActivity<*>,
                        "${it.data?.longitude},${it.data?.latitude}"
                    )
                    it.data?.ticketProducts?.let { ticktes ->
                        if (ticktes.isNotEmpty()) {
                            binding.ticketsLl.visibility = View.VISIBLE
                        }
                        for (ticket in ticktes) {
                            val ticketBinding = ScenicDetailTicketListItemBinding.inflate(
                                layoutInflater,
                                binding.ticketLl,
                                true
                            )
                            ticketBinding.data = ticket
                            ticketBinding.buyDesBtn.setOnClickListener {
                                mode = 1
                                scenicViewModel.getTicketDetail(
                                    ticket.productId,
                                    requireActivity() as BaseTitleBarActivity<*>
                                )
                            }
                            ticketBinding.refundBtn.setOnClickListener {
                                mode = 2
                                scenicViewModel.getTicketDetail(
                                    ticket.productId,
                                    requireActivity() as BaseTitleBarActivity<*>
                                )
                            }
                            ticketBinding.buyBtn.setOnClickListener {
                                if (UserManager.isNotAuthElseTurn(requireContext())) {
                                    return@setOnClickListener
                                }
                                mode = 0
                                scenicViewModel.getTicketDetail(
                                    ticket.productId,
                                    requireActivity() as BaseTitleBarActivity<*>
                                )
                            }
                        }
                    }
                    binding.desRg.setOnCheckedChangeListener { _, id ->
                        if (id == R.id.desRb) {
                            binding.desRb.paint.isFakeBoldText = true
                            binding.desRb.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
                            binding.desRb.setTextColor(ContextCompat.getColor(requireContext() , R.color.new_text_color_1))
                            binding.playRb.setTextColor(ContextCompat.getColor(requireContext() , R.color.new_text_color_3))
                            binding.playRb.paint.isFakeBoldText = false
                            binding.playRb.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
                            binding.richTv.text = Html.fromHtml(
                                it.data?.scenicDescription,
                                GlideImageGetter(binding.richTv),
                                null
                            )
                        } else if (id == R.id.playRb) {
                            binding.desRb.paint.isFakeBoldText = false
                            binding.desRb.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
                            binding.desRb.setTextColor(ContextCompat.getColor(requireContext() , R.color.new_text_color_3))
                            binding.playRb.setTextColor(ContextCompat.getColor(requireContext() , R.color.new_text_color_1))
                            binding.playRb.paint.isFakeBoldText = true
                            binding.playRb.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
                            binding.richTv.text = it.data?.bookNotice
                        }
                    }
                    binding.desRg.check(R.id.desRb)
                }?.onError {
                    findNavController().navigateUp()
                }
            //跳转外部地图
            binding.jumpToMap.setOnClickListener {
                val dialog = SelectItemDialog(
                    requireContext(),
                    scenicViewModel.scenicDetail.value?.data?.longitude,
                    scenicViewModel.scenicDetail.value?.data?.latitude,
                    scenicViewModel.scenicDetail.value?.data?.scenicAddress
                )
                dialog.show()
            }
        }
        scenicViewModel.ticket.observe(viewLifecycleOwner) {
            it?.bindProgressBar(binding.progressBar)
                ?.onComplete {
                    when (mode) {
                        0 ->
                            if (it.data == null || it.data?.priceCalendar.isNullOrEmpty()) {
                                ToastUtils.showLong("没有可售票的日期")
                            } else {
                                showTicketCalender(it.data!!)
                            }

                        1 -> {
                            val dialogBinding = TicketDialogBinding.inflate(layoutInflater)
                            AlertDialog.Builder(requireActivity()).setCancelable(false)
                                .setView(dialogBinding.root)
                                .show().apply {
                                    window?.setBackgroundDrawable(null)
                                    dialogBinding.okBtn.setOnClickListener {
                                        dismiss()
                                    }
                                    dialogBinding.closeBtn.setOnClickListener {
                                        dismiss()
                                    }
                                    dialogBinding.titleTv.text = "购票说明"
                                    dialogBinding.messageTv.text = it.data?.bookNotice
                                }
                        }

                        2 -> {
                            val dialogBinding = TicketDialogBinding.inflate(layoutInflater)
                            AlertDialog.Builder(requireActivity()).setCancelable(false)
                                .setView(dialogBinding.root)
                                .show().apply {
                                    window?.setBackgroundDrawable(null)
                                    dialogBinding.okBtn.setOnClickListener {
                                        dismiss()
                                    }
                                    dialogBinding.closeBtn.setOnClickListener {
                                        dismiss()
                                    }
                                    dialogBinding.titleTv.text = "退改说明"
                                    dialogBinding.messageTv.text = it.data?.refundChangeRule
                                }
                        }
                    }
                }
        }
        scenicViewModel.getScenicDetail(args.id, requireActivity() as BaseTitleBarActivity<*>)
        scenicViewModel.weatherInfo.observe(viewLifecycleOwner) {
            it?.bindProgressBar(binding.progressBar)
                ?.onComplete {
                    val weatherInfoItems = arrayListOf<WeatherInfoItem>()
                    it.data?.casts?.forEachIndexed { index, weatherInfoItem ->
                        if (index < 5) {
                            weatherInfoItems.add(weatherInfoItem)
                        }
                    }
                    (binding.recyclerView.layoutManager as? GridLayoutManager)?.spanCount =
                        weatherInfoItems.size
                    WeatherInfoAdapter(weatherInfoItems).bindToRecyclerView(binding.recyclerView)
                }
        }
        binding.backBtn2.setOnClickListener {
            findNavController().navigateUp()
        }
    }

    private var calendarDialog: BottomSheetDialog? = null
    private var buyDialog: AlertDialog? = null

    private fun showTicketCalender(ticket: Ticket) {
        val dayMap = mapDays(ticket.priceCalendar)
        val dialogBinding = LayoutPriceCalenderBinding.inflate(layoutInflater)
        if (calendarDialog != null) {
            calendarDialog?.dismiss()
        }
        calendarDialog = BottomSheetDialog(requireActivity(), R.style.CalendarDialog).apply {
            dialogBinding.closeBtn.setOnClickListener { calendarDialog?.dismiss() }
            setContentView(dialogBinding.root)
            val mBehavior = BottomSheetBehavior.from(dialogBinding.root.parent as View);
            mBehavior.peekHeight = ScreenUtils.getScreenHeight() / 3 * 2
            mBehavior.maxHeight = ScreenUtils.getScreenHeight() / 3 * 2
            show()
        }
        val adapters = arrayListOf<CalendarAdapter>()
        for (date in dayMap.keys) {
            val calendarBinding = ScenicTicketLayoutItemBinding.inflate(
                layoutInflater,
                dialogBinding.calenderLl,
                true
            )
            calendarBinding.title.text = TimeUtils.date2String(date, "yyyy年MM月")
            val calendarAdapter = CalendarAdapter(buildPriceDays(date, dayMap[date]!!))
            calendarAdapter.bindToRecyclerView(calendarBinding.recyclerView)
            adapters.add(calendarAdapter)
        }
        for (adapter in adapters) {
            adapter.setOnItemClickListener { _, _, position ->
                for (adapter1 in adapters) {
                    val priceDay = adapter.getItem(position)
                    if (priceDay?.settlePriceYbt.isNullOrBlank()) return@setOnItemClickListener
                    adapter1.selectedDay = priceDay
                    adapter1.notifyDataSetChanged()
                }
            }
        }
        dialogBinding.buyBtn.setOnClickListener {
            val selectedDay = adapters[0].selectedDay
            if (selectedDay == null) {
                ToastUtils.showLong("请选择要预约的日期")
                return@setOnClickListener
            }
            var other: Ticket? = null
            val buyBinding = LayoutBuyTicketDesDialogBinding.inflate(layoutInflater)
            buyBinding.ticket = ticket
            buyBinding.priceTv.text = selectedDay.settlePriceYbt
            buyBinding.scenic = scenicViewModel.scenicDetail.value?.data
            buyBinding.dateTv.text = selectedDay.date
            buyBinding.createOrderBtn.setOnClickListener {
                var otherMobile: String? = null
                if (buyBinding.buyRg.checkedRadioButtonId == R.id.buyOtherRb) {
                    if (other != null) {
                        otherMobile = buyBinding.friendMobileEt.text.toString()
                    } else {
                        if (buyBinding.friendMobileEt.text.toString().isBlank()) {
                            ToastUtils.showLong("请输入好友绑定的手机号")
                        } else {
                            ToastUtils.showLong("请点击确认查询账号是否存在")
                        }
                        return@setOnClickListener
                    }
                }
                scenicViewModel.createOrder(
                    requireActivity() as BaseTitleBarActivity<*>,
                    scenicViewModel.scenicDetail.value?.data?.scenicId ?: "",
                    ticket.productId,
                    selectedDay.date ?: "",
                    otherMobile
                )
                buyBinding.createOrderBtn.isEnabled = false
                scenicViewModel.ticketOrder.observe(viewLifecycleOwner) { ticketOrderResult ->
                    ticketOrderResult?.bindProgressBar(binding.progressBar)
                        ?.onComplete {
                            val data = ticketOrderResult.data
                            buyDialog?.dismiss()
                            buyBinding.createOrderBtn.isEnabled = true
                            val payOrderDialogBinding =
                                PayOrderDialogBinding.inflate(layoutInflater)
                            AlertDialog.Builder(requireActivity()).setCancelable(false)
                                .setView(payOrderDialogBinding.root)
                                .setOnDismissListener {
                                    KeyboardUtils.hideSoftInput(requireActivity())
                                }
                                .show().apply {
                                    window?.setBackgroundDrawable(null)
                                    payOrderDialogBinding.closeBtn.setOnClickListener {
                                        KeyboardUtils.hideSoftInput(requireActivity())
                                        dismiss()
                                        findNavController().navigate(
                                            ScenicDetailFragmentDirections.actionScenicDetailFragmentToScenicOrderDetailFragment(
                                                data?.customerOrderNo ?: ""
                                            )
                                        )
                                    }
                                    payOrderDialogBinding.ybtTv.text =
                                        "${selectedDay.settlePriceYbt}yc"
                                    payOrderDialogBinding.passwordEt.setOnCompleteListener { password ->
                                        scenicViewModel.payOrder(
                                            requireActivity() as BaseTitleBarActivity<*>,
                                            data?.customerOrderNo ?: "",
                                            password
                                        )
                                        scenicViewModel.payResult.observe(viewLifecycleOwner) {
                                            it?.bindProgressBar(binding.progressBar)
                                                ?.onComplete(false) {
                                                    KeyboardUtils.hideSoftInput(requireActivity())
                                                    dismiss()
                                                    findNavController().navigate(
                                                        ScenicDetailFragmentDirections.actionScenicDetailFragmentToScenicOrderDetailFragment(
                                                            data?.customerOrderNo ?: ""
                                                        )
                                                    )
                                                }
                                        }
                                    }
                                    payOrderDialogBinding.passwordEt.focus()
                                    payOrderDialogBinding.passwordEt.postDelayed({
                                        KeyboardUtils.showSoftInput(
                                            requireActivity()
                                        )
                                    }, 100)
                                }
                        }
                        ?.onError {
                            buyBinding.createOrderBtn.isEnabled = true
                        }
                }
            }
            fun selectedSelf() {
                buyBinding.ticket = ticket
                buyBinding.friendInfoLl.visibility = View.GONE
                buyBinding.buyerInfoLl.visibility = View.VISIBLE
            }

            fun getFriendSuccess() {
                buyBinding.buyerInfoLl.visibility = View.VISIBLE
                buyBinding.configBtn.text = "取消"
                buyBinding.nameTv.text = other?.idCardName
                buyBinding.idTv.text = other?.idCardNum
                buyBinding.mobileTv.text = other?.mobile
                buyBinding.configBtn.setOnClickListener {
                    other = null
                    buyBinding.friendMobileEt.setText("")
                    buyBinding.configBtn.text = "确定"
                    buyBinding.friendMobileEt.isEnabled = true
                    buyBinding.configBtn.setOnClickListener {
                        val friendMobile = buyBinding.friendMobileEt.text.toString()
                        if (friendMobile.isBlank()) {
                            ToastUtils.showLong("请输入好友绑定的手机号")
                            return@setOnClickListener
                        }
                        scenicViewModel.getFriendInfo(
                            requireActivity() as BaseTitleBarActivity<*>,
                            friendMobile
                        )
                        scenicViewModel.ticketFriend.observe(viewLifecycleOwner) {
                            it?.bindProgressBar(binding.progressBar)
                                ?.onComplete {
                                    other = it.data
                                    getFriendSuccess()
                                }
                        }
                    }
                    buyBinding.buyerInfoLl.visibility = View.GONE
                }
                buyBinding.friendMobileEt.isEnabled = false
            }

            if (ticket.isHasTask6 == "1") {
                buyBinding.buyOtherLl.visibility = View.VISIBLE
                buyBinding.buyRg.setOnCheckedChangeListener { _, checkedId ->
                    if (checkedId == R.id.buyselfRb) {
                        selectedSelf()
                        buyBinding.buyOhterDesTv.visibility = View.GONE
                    } else {
                        buyBinding.buyOhterDesTv.visibility = View.VISIBLE
                        buyBinding.friendInfoLl.visibility = View.VISIBLE
                        if (other != null) {
                            getFriendSuccess()
                        } else {
                            buyBinding.configBtn.text = "确定"
                            buyBinding.friendMobileEt.isEnabled = true
                            buyBinding.configBtn.setOnClickListener {
                                val friendMobile = buyBinding.friendMobileEt.text.toString()
                                if (friendMobile.isBlank()) {
                                    ToastUtils.showLong("请输入好友绑定的手机号")
                                    return@setOnClickListener
                                }
                                scenicViewModel.getFriendInfo(
                                    requireActivity() as BaseTitleBarActivity<*>,
                                    friendMobile
                                )
                                scenicViewModel.ticketFriend.observe(viewLifecycleOwner) {
                                    it?.bindProgressBar(binding.progressBar)
                                        ?.onComplete {
                                            other = it.data
                                            getFriendSuccess()
                                        }
                                }
                            }
                            buyBinding.buyerInfoLl.visibility = View.GONE
                        }
                    }
                }
            } else {
                buyBinding.buyOtherLl.visibility = View.GONE
            }
            buyDialog?.dismiss()
            buyDialog =
                AlertDialog.Builder(requireActivity()).setCancelable(false).setView(buyBinding.root)
                    .show().apply {
                        window?.setBackgroundDrawable(null)
                        calendarDialog?.dismiss()
                        buyBinding.closeBtn.setOnClickListener { dismiss() }
                    }
        }
    }

    private fun buildPriceDays(
        date: Date,
        priceDays: java.util.ArrayList<PriceDay>
    ): java.util.ArrayList<PriceDay> {
        val allPriceDays = arrayListOf<PriceDay>()
        val first = TimeUtils.getUSWeek(date)
        val firstDay = Calendar.getInstance(Locale.CHINA).also { it.time = date }
        val firstIndex = getFirstIndex(first)
        var firstFilled = false
        for (i in 0..42) {
            if (i < 7 && !firstFilled) {
                if (i == firstIndex) {
                    firstFilled = true;
                    val dateString = TimeUtils.date2String(firstDay.time, "yyyy-MM-dd")
                    allPriceDays.add(
                        PriceDay(
                            findYbt(dateString, priceDays),
                            dateString,
                            firstDay.time
                        )
                    )
                } else {
                    allPriceDays.add(PriceDay("", "", Date()))
                }
            } else {
                val beforeMonth = firstDay.get(Calendar.MONTH)
                firstDay.add(Calendar.DAY_OF_MONTH, 1)
                val afterMonth = firstDay.get(Calendar.MONTH)
                if (beforeMonth != afterMonth) {
                    break
                }
                val dateString = TimeUtils.date2String(firstDay.time, "yyyy-MM-dd")
                allPriceDays.add(
                    PriceDay(
                        findYbt(dateString, priceDays),
                        dateString,
                        firstDay.time
                    )
                )
            }
        }
        return allPriceDays
    }

    private fun findYbt(dateString: String?, allPriceDays: java.util.ArrayList<PriceDay>): String? {
        for (priceDay in allPriceDays) {
            if (priceDay.date == dateString) {
                return priceDay.settlePriceYbt;
            }
        }
        return ""
    }

    private fun getFirstIndex(first: String?): Int {
        when (first) {
            "Sunday" -> return 0
            "Monday" -> return 1
            "Tuesday" -> return 2
            "Wednesday" -> return 3
            "Thursday" -> return 4
            "Friday" -> return 5
            "Saturday" -> return 6
        }
        return 0
    }

    private fun mapDays(days: ArrayList<PriceDay>): HashMap<Date, ArrayList<PriceDay>> {
        val dayMap = HashMap<Date, ArrayList<PriceDay>>()
        for (day in days) {
            val date = TimeUtils.string2Date(day.date, "yyyy-MM")
            if (dayMap.containsKey(date)) {
                dayMap[date]?.add(day)
            } else {
                dayMap[date] = arrayListOf(day)
            }
        }
        return dayMap
    }

}